package com.lagou.config;

import com.lagou.test.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();
//        List<Element> list = rootElement.elements("//property");
        List<Element> list = rootElement.selectNodes("//property");

        if (list == null || list.size() == 0) {
            throw new RuntimeException("配置信息读取失败");
        }

        Properties properties = new Properties();
        for (Element element : list) {
            properties.setProperty(element.attributeValue("name"), element.attributeValue("value"));
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);

//        List<Element> elementList = rootElement.elements("//mapper");
        List<Element> elementList = rootElement.selectNodes("//mapper");
        for (Element element : elementList) {
            InputStream resourceAsStream = Resources.getResourceAsStream(element.attributeValue("resource"));
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parseSingleMapper(resourceAsStream);
        }

        return configuration;
    }
}
